/**
 * 
 */
package com.gua.jbs.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gua.jbs.bean.CouponBean;
import com.gua.jbs.bean.CustomerBean;
import com.gua.jbs.bean.OrderBean;
import com.gua.jbs.bean.ProductBean;
import com.gua.jbs.service.ICouponService;
import com.gua.jbs.service.ICustomerService;
import com.gua.jbs.service.IInvoiceService;
import com.gua.jbs.service.IOrderService;
import com.gua.jbs.service.IProductService;
import com.gua.jbs.service.IStockService;
import com.gua.jbs.serviceImpl.CouponService;
import com.gua.jbs.serviceImpl.CustomerService;
import com.gua.jbs.serviceImpl.InvoiceService;
import com.gua.jbs.serviceImpl.OrderService;
import com.gua.jbs.serviceImpl.ProductService;
import com.gua.jbs.serviceImpl.StockService;
import com.gua.jbs.utility.ApplicationConstant;
import com.gua.jbs.utility.ApplicationException;
import com.gua.jbs.utility.CollectionUtil;
import com.gua.jbs.utility.DBConstant;
import com.gua.jbs.utility.ExceptionMessage;
import com.gua.jbs.utility.StringUtil;

/**
 * Controller related to the addition of a Customer Bill in the system, edit and
 * delete functionality
 * 
 * @author Yogesh
 * 
 */
public class BillController extends BaseController {

	private static final Logger logger = Logger.getLogger(BillController.class);

	private ICustomerService customerService = null;
	private IProductService productService = null;
	private IStockService stockService = null;
	private ICouponService couponService = null;
	private IOrderService orderService = null;
	private IInvoiceService invoiceService = null;

	public BillController() {
		customerService = new CustomerService();
		productService = new ProductService();
		stockService = new StockService();
		couponService = new CouponService();
		orderService = new OrderService();
		invoiceService = new InvoiceService();
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Get the action parameter to understand the type of request
		String action = request.getParameter(ApplicationConstant.ACTION);

		if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.BILL_SHOW)) {
			request.setAttribute("address", ApplicationConstant.SIYORA_ADDRESS);
			request.setAttribute("mobile", ApplicationConstant.SIYORA_MOBILE);
			request.setAttribute("emailId", ApplicationConstant.SIYORA_EMAIL);

			List<String> paymentModeList = new ArrayList<String>();
			paymentModeList.add(ApplicationConstant.PAYMENT_MODE_CASH);
			paymentModeList.add(ApplicationConstant.PAYMENT_MODE_CREDIT_CARD);
			paymentModeList.add(ApplicationConstant.PAYMENT_MODE_DEBIT_CARD);
			paymentModeList.add(ApplicationConstant.PAYMENT_MODE_COD);
			paymentModeList.add(ApplicationConstant.PAYMEN_MODE_NET);
			paymentModeList.add(ApplicationConstant.PAYMEN_MODE_ON_APPROVAL);
			request.setAttribute("paymentModes", paymentModeList);
			try {
				List<String> invoiceCounter = invoiceService.generatedInvoice();
				if (!CollectionUtil.isEmptyList(invoiceCounter)) {
					request.setAttribute("invoice", "" + invoiceCounter.get(2));
					logger.info("INVOICE : " + invoiceCounter.get(2));
				}
			} catch (ApplicationException ae) {

			}
			rd = request.getRequestDispatcher("pages/jsp/newBill.jsp");
			rd.forward(request, response);

		} else if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.GENERATE_BILL)) {
			String custName = request
					.getParameter(ApplicationConstant.custName);
			String custAddress = request
					.getParameter(ApplicationConstant.custAddress);
			String custMobile = request
					.getParameter(ApplicationConstant.custMobile);
			String emailAddress = request
					.getParameter(ApplicationConstant.emailAddress);
			String productTotalAmount = request
					.getParameter(ApplicationConstant.TOTAL_AMOUNT);
			String invoiceNumber = request
					.getParameter(ApplicationConstant.INVOICE_NO);
			String finalPrice = request
					.getParameter(ApplicationConstant.FINAL_AMOUNT);
			String courierCharges = request
					.getParameter(ApplicationConstant.courierCharges);
			String discount = request
					.getParameter(ApplicationConstant.discount);
			String serviceTax = request
					.getParameter(ApplicationConstant.SERIVCE_TAX);
			String orderInfo = request
					.getParameter(ApplicationConstant.CUST_PROD_INFO);
			String refNo = request
					.getParameter(ApplicationConstant.REF_NO);
			
			try {

				// Call the Order service to create map of order details from
				// Json
				Map<String, List<String>> orderContent = orderService
						.prepareOrderContentMap(orderInfo);

				/**
				 * STEP 1: Create the new customer if not exist
				 */
				CustomerBean customerBean = new CustomerBean();
				customerBean.setName(custName);
				customerBean.setAddress(custAddress);
				customerBean.setContactNo(custMobile);
				customerBean.setEmailAddress(emailAddress);
				String customerId = null;
				String msgCustBill = "";
				String custPayMode = request
						.getParameter(ApplicationConstant.custPayMode);

				// Call the customer service to add the customer details in
				// database
				customerId = customerService.addCustomerForBill(customerBean);

				/**
				 * STEP 2: Create new Order Object with all product details
				 */
				OrderBean orderObject = new OrderBean();
				orderObject.setCustomerId(customerId);
				if (StringUtil.isNullOrEmpty(serviceTax))
					orderObject.setOrderServiceTax(Double
							.parseDouble(serviceTax));
				if (custPayMode != null)
					orderObject.setPaymentMode(custPayMode);
				orderObject.setInvoiceNumber(invoiceNumber);
				orderObject.setTotalPrice(productTotalAmount);
				orderObject.setCourierCharges(courierCharges);
				orderObject.setOrderContentMap(orderContent);
				orderObject.setDiscountPerc(discount);
				orderObject.setFinalPrice(finalPrice);
				orderObject.setReference(refNo);

				// Call the service layer to process the order
				orderService.prepareOrder(orderObject);
				JSONObject obj = new JSONObject();
				
				obj.put("message", "success");
				logger.info("obj===" + obj);
				PrintWriter writer = response.getWriter();
				writer.print(obj.toString());
				/*rd = request.getRequestDispatcher("/pages/jsp/newBill.jsp");
				rd.forward(request, response);*/
			} catch (ApplicationException e) {

			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			request.setAttribute("message",
					ExceptionMessage.MISSING_PRODUCT_CODE);
			rd = request.getRequestDispatcher("/pages/jsp/newBill.jsp");
			rd.forward(request, response);
			try{
				JSONObject obj = new JSONObject();
			
				obj.put("message", ExceptionMessage.MISSING_PRODUCT_CODE);
				logger.info("obj===" + obj);
				PrintWriter writer = response.getWriter();
				writer.print(obj.toString());
				
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
}
